package com.bawei.lib_cache.sp

import android.content.Context
import android.content.SharedPreferences
import com.baway.cache.ICache
import com.bawei.lib_base.BaseApp
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

/**
 * 使用Sp来实现
 *
 *  * 面试题：apply()和和commit()的区别
 *  * 1.commit()有返回值,true代表保存成功，false代表保存失败，apply()没有返回值
 *  * 2.commit()属于同步提交，会阻塞主线程，applu()属于异步提交，不会阻塞主线程，但是当数据太大或者太多的情况下，也有可能执行时间过长，也会有可能ANR问题
 *  *3.commmit()保存立即生效,apply()会合并多次操作,不确保数据是否保存成功
 */
object KVSpCache: ICache {

    private lateinit var msP:SharedPreferences
     private val sp_name=""
    init {
        if(msP==null){
            //sp官方不建议设置为多进程访问模式,通常使用私有模式,仅当前应用访问
           msP=BaseApp.appContext.getSharedPreferences("video_sp",Context.MODE_PRIVATE)
        }

    }



    override fun putString(key: String, value: String) {
        if(msP==null){
            throw RuntimeException("video_sp SharedPrefences is not init!")
        }
        //获取edit编辑器
        msP.edit()?.putString(key,value)?.apply()
    }

    override fun putInt(key: String, value: Int) {
        if(msP==null){
            throw RuntimeException("video_sp SharedPrefences is not init!")
        }
        //获取edit编辑器
        msP.edit()?.putInt(key,value)?.apply()
    }

    override fun putLong(key: String, value: Long) {
        if(msP==null){
            throw RuntimeException("video_sp SharedPrefences is not init!")
        }
        //获取edit编辑器
        msP.edit()?.putLong(key,value)?.apply()
    }

    override fun putBool(key: String, value: Boolean) {
        if(msP==null){
            throw RuntimeException("video_sp SharedPrefences is not init!")
        }
        //获取edit编辑器
        msP.edit()?.putBoolean(key,value)?.apply()
    }

    override fun getString(key: String): Flow<String> {
       return flow {
           msP.getString(key,"").toString()
       }
    }

    override fun getInt(key: String): Flow<Int> {
        return flow {
            msP.getInt(key,0)
        }
    }

    override fun getLong(key: String): Flow<Long> {
        return flow {
            msP.getLong(key,0)
        }

    }

    override fun getBool(key: String): Flow<Boolean> {
        return flow {
            msP.getBoolean(key,false)
        }
    }
}